package com.suse.service.view.order.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson2.JSONObject;
import com.github.wxpay.sdk.WXPayUtil;
import com.suse.common.config.response.ApiException;
import com.suse.common.config.response.R;
import com.suse.common.config.response.SimpleCode;
import com.suse.common.util.core.StringUtil;
import com.suse.common.util.date.DateUtil;
import com.suse.service.view.order.constant.OrderConstant;
import com.suse.service.view.order.entity.Order;
import com.suse.service.view.order.entity.PayLog;
import com.suse.service.view.order.mapper.OrderPayLogMapper;
import com.suse.service.view.order.service.PayLogService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.suse.service.view.order.service.OrderService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 支付日志 服务实现类
 * </p>
 *
 * @author 辜玉彬
 * @since 2022-08-20
 */
@Service
public class PayLogServiceImpl extends ServiceImpl<OrderPayLogMapper, PayLog> implements PayLogService {

    @Resource
    private OrderService orderService;

    @Override
    public R generateNative(String orderNo) {
        Order order = orderService.lambdaQuery()
                .eq(Order::getOrderNo, orderNo)
                .one();
        // 封装请求参数
        HashMap<String, String> param = new HashMap<>();
        param.put("appid","wx74862e0dfcf69954");
        param.put("mch_id","1558950191");
        param.put("nonce_str", WXPayUtil.generateNonceStr());
        param.put("body",order.getCourseTitle());
        param.put("out_trade_no",orderNo);
        // 测试价格(分)
        param.put("total_fee","1");
        param.put("spbill_create_ip","127.0.0.1");
        param.put("notify_url","http://localhost:9003/dev-api/view/order/payLog/notify");
        param.put("trade_type","NATIVE");
        // 获取微信支付二维码
        try {
            // 发送 https 请求
            String xml = HttpRequest.post("https://api.mch.weixin.qq.com/pay/unifiedorder")
                    .body(WXPayUtil.generateSignedXml(param, "T6m9iK73b0kn9g5v426MKfHQH7X8rKwb"))
                    .execute()
                    .body();
            Map<String, String> map = WXPayUtil.xmlToMap(xml);
            System.out.println(map);
            // 订单支付二维码
            HashMap<String, Object> nativeVo = new HashMap<>();
            nativeVo.put("out_trade_no",orderNo);
            nativeVo.put("course_id",order.getCourseId());
            nativeVo.put("total_fee","0.01");
            nativeVo.put("result_code",map.get("result_code"));
            nativeVo.put("code_url",map.get("code_url"));
            nativeVo.put("orderNo",orderNo);
            return R.success(nativeVo);
        } catch (Exception e) {
            e.printStackTrace();
            throw new ApiException("支付二维码生成是失败!");
        }
    }

    @Override
    public R getPayStatus(String orderNo) {
        // 封装请求参数
        HashMap<String, String> param = new HashMap<>();
        param.put("appid","wx74862e0dfcf69954");
        param.put("mch_id","1558950191");
        param.put("nonce_str", WXPayUtil.generateNonceStr());
        param.put("out_trade_no",orderNo);
        // 获取微信支付状态
        try {
            String xml = HttpRequest.post("https://api.mch.weixin.qq.com/pay/orderquery")
                    .body(WXPayUtil.generateSignedXml(param, "T6m9iK73b0kn9g5v426MKfHQH7X8rKwb"))
                    .execute()
                    .body();
            Map<String, String> map = WXPayUtil.xmlToMap(xml);
            if (CollectionUtil.isEmpty(map)) {
                throw new ApiException("订单支付失败！");
            }
            String tradeState = map.get("trade_state");
            if (StringUtil.isEquals(tradeState,"SUCCESS")) {
                // 支付成功
                // 更新订单状态
                orderService.updateStatusByOrderNo(orderNo, OrderConstant.PAID);
                // 添加支付记录
                PayLog payLog = new PayLog();
                payLog.setOrderNo(orderNo);  // 订单号
                payLog.setPayTime(DateUtil.now());   //
                payLog.setPayType(OrderConstant.WX);
                payLog.setPrice(new BigDecimal("0.01"));
                payLog.setTradeState(map.get("trade_state"));
                payLog.setTransactionId(map.get("transaction_id"));
                payLog.setAttr(JSONObject.toJSONString(map));
                return R.success("支付成功");
            }
            return R.success(SimpleCode.PAYING);
        } catch (Exception e) {
            e.printStackTrace();
            throw new ApiException("订单支付失败！");
        }
    }

}
